package com.dhnsoft.shortLink.optional;

import com.dhnsoft.shortLink.stream.Author;
import com.dhnsoft.shortLink.stream.Book;
import org.junit.jupiter.api.Test;

import java.util.List;
import java.util.Optional;

/**
 * ClassName: OptionalDemo
 * Package: com.dhnsoft.shortLink.optional
 * Description:
 *
 * @Author dhn
 * @Create 2024/4/3 20:35
 * @Version 1.0
 */
public class OptionalDemo {

    @Test
    public void test01(){
        Optional<Author> author = getAuthor();
        System.out.println(author.orElseGet(() -> new Author(1L, "蒙多", 17, "一个祖安人", null)));
    }

    /**
     * orElseGet
     * */
    @Test
    public void test02(){
        Optional<Author> author = getAuthor();
        System.out.println(author.orElseGet(() -> new Author(1L, "蒙多", 17, "一个祖安人", null)));
    }


    /**
     * orElseThrow
     * */
    @Test
    public void test03() throws Throwable {
        Optional<Author> author = getAuthor();
        System.out.println(author.orElseThrow(() -> new Throwable("数据为null")));
    }

    /**
     * filter
     * */
    @Test
    public void test04() throws Throwable {
        Optional<Author> author = getAuthor();
        System.out.println(author.filter(author1 -> author1.getAge() > 15));
    }

    /**
     * ifPresent()
     * */
    @Test
    public void test05() throws Throwable {
        Optional<Author> author = getAuthor();
        author.filter(item -> item.getAge() > 12).ifPresent(item-> System.out.println(item));
    }

    /**
     * map
     * */
    @Test
    public void test06() throws Throwable {
        Optional<Author> author = getAuthor();
        Optional<List<Book>> books = author.map(item -> item.getBooks());
        books.ifPresent(item-> System.out.println(item));
    }

    public  Optional<Author> getAuthor(){
        Author  author = new Author(1L, "蒙多", 17, "一个祖安人", null);
        return Optional.ofNullable(author);
    }
}
